package com.tao.service.impl;

import com.tao.entity.LoginUser;
import com.tao.entity.User;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.exception.SystemException;
import com.tao.service.LoginService;
import com.tao.utils.BeanCopyUtils;
import com.tao.utils.JwtUtils;
import com.tao.utils.RedisCache;
import com.tao.vo.ResponseResult;
import com.tao.vo.UserInfoVo;
import com.tao.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author 季伟
 * 功能：
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager ;
    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User loginUser) {

        //创建用来认证的authentication，它封装了用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser.getUserName(),loginUser.getPassword());
        //使用AuthenticationManager的authenticate方法进行用户认证，这个方法内部会调用一个UserDetailService进行用户信息获取
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);//调用该方法进行验证
        if (Objects.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR,"用户认证失败");
        }
        //principal是一个userDetail对象也就是userDetailService返回的值。
        LoginUser userDetails = (LoginUser) authenticate.getPrincipal();

        //利用jwt创建 token
        String token = JwtUtils.createJWT(userDetails.getCacheUser().getId().toString());
        userDetails.setToken(token);
        redisCache.setCacheObject("login:"+userDetails.getCacheUser().getId(),userDetails,1, TimeUnit.HOURS);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(userDetails.getUser(),UserInfoVo.class);
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setToken(token);
        userLoginVo.setUserInfo(userInfoVo);
        return new ResponseResult(200,"登录成功",userLoginVo);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getCacheUser().getId();
        boolean isDeleted = redisCache.deleteObject("login:"+userId);
        if (isDeleted){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),"注销成功！");
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"注销失败");
        }

    }

}
